#include "PrecompiledHeader_Engineer.h"
#include "WWeather.h"

/*--------------------------------------------------------------------------*/

WWeather::WWeather()
{
	this->m_sun = NULL;

	this->m_totalDayMinute = 700.0f;
}

/*--------------------------------------------------------------------------*/

WWeather::~WWeather()
{
	delete this->m_sun;
}

/*--------------------------------------------------------------------------*/

void WWeather::SetTime(float total)
{
	this->m_totalDayMinute = total;

	if (this->m_totalDayMinute > 1440.0f)
	{
		this->m_totalDayMinute = 0.0f;
	}
	else if (this->m_totalDayMinute < 0.0f)
	{
		this->m_totalDayMinute = 0.0f;
	}

	this->UpdateSunDirection();
}

/*--------------------------------------------------------------------------*/

void WWeather::UpdateSunDirection()
{
	float total = this->m_totalDayMinute / 1440.0f;
	total *= glm::pi<float>() * 2.0f;

	float c = glm::cos(total);
	float s = glm::sin(total);

	this->m_sun->SetAmbient(Color(-c, -c, -c));
	this->m_sun->SetDirection(glm::vec3(s, 0.0f, c));

	EffectColormatrix* cm = EffectColormatrix::getInstance();

	float n[16] = {0.7f, 0.0f, 0.0f, 0.0f,    0.0f, 0.7f, 0.0f, 0.0f,    0.4f, 0.4f, 1.0f, 0.0f,      0.0f, 0.0f, 0.0f, 1.0f };
	float d[16] = {1.0f, 0.0f, 0.0f, 0.0f,    0.0f, 1.0f, 0.0f, 0.0f,    0.0f, 0.0f, 1.0f, 0.0f,      0.0f, 0.0f, 0.0f, 1.0f };

	float r = (-c + 1.0f) * 0.5f;

	if (r < 0.0f)
	{
		r = 0.0f;
	}

	cm->SetColorMatrix(glm::make_mat4x4(d) * r + glm::make_mat4x4(n) * (1.0f - r));
}

/*--------------------------------------------------------------------------*/

float WWeather::GetTime() const
{
	return this->m_totalDayMinute;
}

/*--------------------------------------------------------------------------*/

void WWeather::OnLevelLoad(const std::string& level)
{
	this->m_sun = new DirectionalLight();
	this->m_sun->SetDirection(glm::vec3(0.0f, 0.0f, 1.0f));
	this->m_sun->SetAmbient(Color(0.5f, 0.5f, 0.5f));
	this->m_sun->SetDiffuse(Color(1.0f, 1.0f, 1.0f));
	this->m_sun->SetSpecular(vl::White);
	this->m_sun->SetName("sun");

	this->m_sun->SetParent(CTree::getInstance()->GetRoot());
}

/*--------------------------------------------------------------------------*/

void WWeather::OnLevelUnload()
{
	CTree::getInstance()->DeleteObject(this->m_sun);
}

/*--------------------------------------------------------------------------*/

void WWeather::OnLevelCalc()
{
	this->m_totalDayMinute += CSdl::getInstance()->GetDeltaTime() * 10.0f;
	this->UpdateSunDirection();
}

/*--------------------------------------------------------------------------*/
